package com.iweb.dao;

import com.iweb.pojo.Community;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/*
 *作者：lth
 *时间：2020/8/12 18:18
 *描述：
 */
public class CommunityDaoImpl implements CommunityDao {
    private Connection connection;
    private PreparedStatement pst;
    private ResultSet rs;

    public CommunityDaoImpl(Connection connection) {
        this.connection = connection;
    }

    @Override
    public List<Community> findAll() throws Exception {
        List<Community> communities = new ArrayList<>();
        Community community = null;
        String sql = "select * from tb_community";
        pst = connection.prepareStatement(sql);
        rs = pst.executeQuery();
        while (rs.next()) {
            community = createInstance(rs);
            communities.add(community);
        }
        return communities;
    }

    @Override
    public Community selectByUsername(String username) throws Exception {
        Community community = null;
        String sql = "select * from tb_community where username=?";
        pst=connection.prepareStatement(sql);
        pst.setString(1,username);
        rs=pst.executeQuery();
        while (rs.next()){
            community=createInstance(rs);
        }
        return community;
    }

    @Override
    public Integer updateByName(String username,Integer type) throws Exception{
        String sql=null;
        if (type==0){
            sql="UPDATE tb_community SET zans=zans+1 WHERE username=?";
            type=1;
        }
        else if (type==1){
            sql="UPDATE tb_community SET zans=zans-1 WHERE username=?";
            type=0;
        }
        pst=connection.prepareStatement(sql);
        pst.setString(1,username);
        pst.executeUpdate();
        return type;
    }

    private Community createInstance(ResultSet rs) throws Exception {
        Community community = new Community();
        community.setUsername(rs.getString(1));
        community.setPhonetype(rs.getString(2));
        community.setContent(rs.getString(3));
        community.setTopic(rs.getString(4));
        community.setCircle(rs.getString(5));
        community.setZans(rs.getString(6));
        return community;
    }
}
